<template>
	<view class="page-info">
		<uni-load-more status="loading" v-if="loading" style="margin-top: 30px;"></uni-load-more>

		<view v-if="!loading">
			<view class="top-info">
				<image src="/static/image/icon2/wifi.png" class="icon" mode="widthFix"></image>
				<view class="name">
					<view>{{businessInfo.storeWifiName}}</view>
					<view class="tip">一键链接，安全快捷</view>
				</view>
			</view>
			<view class="icon-gif" v-if="active!=-1">
				<image src="/static/wifi.gif" mode="widthFix"></image>
				<uni-steps :options="list1" active-color="#000" :active="active" direction="column" />
			</view>
			<view class="mian-btn" @tap="clickWifi" v-if="businessInfo&&btnType">
				{{btnType==1?'一键安全连接WIFI':'正在连接WIFI'}}
			</view>
			<view class="btn-info-order" style="padding-top: 20px;">
				<view class="tips">领个红包，买单少付点儿</view>
				<view class="bio" @tap="goOrder">
					<text style="line-height: 18px;font-weight: bold;">马上去领</text>
					<image src="/static/vd.png" mode="widthFix" style="width: 26px;margin-left:7px;"></image>
				</view>
			</view>
		</view>
		<ad unit-id="adunit-0daff0d411198872" ad-type="video" ad-theme="white"></ad>
	</view>
</template>

<script>
	let videoAd = null

	// 在页面中定义插屏广告
	let interstitialAd = null
	const app = getApp();
	import easyLoadimage from '@/components/easy-loadimage/easy-loadimage.vue'
	export default {
		components: {
			easyLoadimage
		},
		data() {
			return {
				businessInfo: null,
				btnType: 1,
				active: -1,
				list1: [{
					title: '建立连接'
				}, {
					title: '分配ip地址'
				}, {
					title: '安全检测'
				}, {
					title: '联网检测'
				}],
				loading: true,
				timeInfo: 3500,
				isGoInfo: true,
				userKey: null,
				rateNum: null,
				myBusId: null,
				busPage: 1,
				location: null,
				goodsList: [],
				busMore: true,
				scrollTop: 0,
				picServiceUrl: app.globalData.picServiceUrl,
			}
		},
		onLoad(ops) {
			if (ops && ops.id) {
				this.businessId = ops.id;
				this.isGoInfo = false;
			} else {
				let info;
				//#ifdef  MP-WEIXIN
				info = decodeURIComponent(ops.q);
				// #endif

				//#ifdef  MP-ALIPAY
				info = app.globalData.qrCode;
				// #endif
				if (info) {
					// this.businessId = info.split('id=')[1];
					let pam = info.split('id=')[1];
					let arr = pam.split('_')
					this.businessId = arr[0]
					if (arr.length == 3) {
						this.rateNum = arr[1]
						this.myBusId = arr[2]
					}
				}
			}
			if (wx.createRewardedVideoAd) {
				videoAd = wx.createRewardedVideoAd({
					adUnitId: 'adunit-ad417c6c04eaeac2'
				})
				videoAd.onLoad(() => {})
				videoAd.onError((err) => {})
				videoAd.onClose((res) => {
					// 用户点击了【关闭广告】按钮
					if (res && res.isEnded) {
						// 正常播放结束，可以下发游戏奖励
						uni.request({
							url: app.globalData.serviceUrl +
								'/UserMiniProgramController/getAdPrice',

							method: 'POST',
							data: {
								key: this.userKey
							},
							header: {
								'content-type': 'application/x-www-form-urlencoded'
							},
							success: res => {
								var data = res.data;
								if (data.state == 1) {
									uni.showToast({
										title: "红包到手啦，去逛逛",
										icon: "none"
									})
									setTimeout(() => {
										uni.navigateTo({
											url: "/pages/newIndex/newIndex"
										})
									}, 1500)

								} else {
									uni.showToast({
										title: res.data.notice,
										icon: "none"
									})
								}
							}
						});

					} else {
						// uni.showToast({
						// 	title: "看完广告才能连接哦~",
						// 	icon: "none"
						// })
					}
				})
			}




			// 在页面onLoad回调事件中创建插屏广告实例
			if (wx.createInterstitialAd) {
				interstitialAd = wx.createInterstitialAd({
					adUnitId: 'adunit-c8481d90dddb3264'
				})
				interstitialAd.onLoad(() => {})
				interstitialAd.onError((err) => {})
				interstitialAd.onClose(() => {})
			}

			this.getBusiness();
			this.loginInit();

			this.getGps();
			this.getOfflineBusinessInfoList();
		},
		methods: {
			loginInit() {
				uni.login({
					success: (res) => {
						uni.request({
							url: app.globalData.serviceUrl + '/loge',
							data: {
								code: res.code
							},
							method: 'POST',
							header: {
								'content-type': 'application/x-www-form-urlencoded'
							},
							success: (res) => {
								if (res.data.state == 1) {
									this.userKey = res.data.notice;
								} else {
									uni.showToast({
										title: res.data.notice,
										icon: "none",
										duration: 2000
									});
								}

							},

						});

					}
				});
			},
			goOrder() {
				if (videoAd) {
					videoAd.show().catch(() => {
						// 失败重试
						videoAd.load()
							.then(() => videoAd.show())
							.catch(err => {
								console.log('激励视频 广告显示失败')
							})
					})
				}

			},
			goOrderPage() {
				setTimeout(() => {
					uni.navigateTo({
						url: "/pages/qrCode/qrCode?id=" + this
							.businessInfo.id
					})
				}, 1500)
			},
			clickWifi() {
				// 在适合的场景显示插屏广告
				if (interstitialAd) {
					setTimeout(() => {
						interstitialAd.show().catch((err) => {
							console.error(err)
						})
					}, 3000)
				}
				if (this.btnType == 1) {
					this.btnType = 2;
					this.active = 0;
					let intver = setInterval(() => {
						if (this.active == 3) {
							clearInterval(intver);
							this.goWifi();
						}
						this.active++;
					}, this.timeInfo)
				}

			},
			goWifi() {
				setTimeout(() => {
					this.btnType = 1;
					this.active = -1;
				}, this.timeInfo)

				let SSID = this.businessInfo.storeWifiName;
				let password = this.businessInfo.storeWifiPassword;
				let that = this;
				wx.startWifi({
					success() {
						wx.getConnectedWifi({
							success: (res) => {
								if (res.errCode == 0 && SSID == res.wifi.SSID) {
									return uni.showToast({
										title: "已连接",
										icon: "success"
									})
								}
							}
						})
						wx.connectWifi({
							SSID,
							password,
							success() {
								wx.onWifiConnected(result => {
									if (result.wifi.SSID === SSID) {
										uni.showToast({
											title: '连接成功',
											icon: 'success',
											duration: 2000
										})
									} else {
										// 连接失败
										that.tipByState(e.errCode);
									}
								})
							},
							fail(e) {
								// 连接失败
								console.log(e);
								that.tipByState(e.errCode);
							}
						})
					},
					fail(e) {
						console.log(e);
						that.tipByState(e.errCode);
					}
				})
			},
			tipByState(state) {
				uni.stopWifi({
					success(res) {
						console.log(res.errMsg)
					}
				})
				switch (state) {
					case 12001:
						uni.showToast({
							title: "当前系统不支持相关能力",
							icon: "none"
						})
						break;
					case 12002:
						uni.showToast({
							title: "密码错误",
							icon: "none"
						})
						break;
					case 12003:
						uni.showToast({
							title: "连接失败，请稍后再试",
							icon: "none"
						})
						break;
					case 12004:
						uni.showToast({
							title: "连接失败，请稍后再试",
							icon: "none"
						})
						break;
					case 12005:
						uni.showToast({
							title: "未打开 Wi-Fi 开关",
							icon: "none"
						})
						break;
					case 12006:
						uni.showToast({
							title: "未打开 GPS 定位开关",
							icon: "none"
						})
						break;
					case 12007:
						uni.showToast({
							title: "用户拒绝授权链接 Wi-Fi",
							icon: "none"
						})
						break;
					case 12007:
						uni.showToast({
							title: "无效Wi-Fi名称",
							icon: "none"
						})
						break;
					default:
						uni.showToast({
							title: "连接失败，请稍后再试",
							icon: "none"
						})
						break;
				}
			},
			getBusiness() {
				uni.request({
					url: app.globalData.serviceUrl + '/UserMiniProgramController/getOfflineBusinessInfoById',
					data: {
						offlineBusinessId: this.businessId
					},
					method: 'POST',
					header: {
						'content-type': 'application/x-www-form-urlencoded'
					},
					success: (res) => {

						if (res.data.state == 1 && res.data.data.storeWifiName) {
							this.businessInfo = res.data.data;
							uni.setClipboardData({
								data: this.businessInfo.businessCustomVideoLink,
								success: function() {
									uni.hideToast()
								}
							});
							setTimeout(() => {
								this.loading = false
							}, this.timeInfo)
						} else {
							if (this.isGoInfo) {
								uni.navigateTo({
									url: "/pages/newMy/generateCode/generateCode?id=" + this
										.businessId + '&rate=' + this.rateNum + '&sharid=' + this
										.myBusId
								})
							}
						}

					}
				});
			},
			getGps() {
				var that = this;
				uni.getLocation({
					type: 'gcj02',
					altitude: true,

					success(res) {
						that.location = res;
						that.getOfflineBusinessInfoList();
					},

					fail(ff) {
						//用户拒绝授权
						uni.getSetting({
							success: function(res) {
								if (!res.authSetting['scope.userLocation']) {
									uni.showModal({
										title: '提示',
										content: '拒绝授权位置信息，将无法获取您附近商家信息',
										confirmText: '去设置',

										success(res) {
											if (res.confirm) {
												uni.openSetting({
													success(res) {
														var info = res.authSetting;
														console.log(res)
														if (res.authSetting[
																'scope.userLocation'
															]) {
															that.getGps();
														}
													}
												});
											} else {
												if (res.cancel) {
													that.getOfflineBusinessInfoList();
												}
											}
										}
									});
								}
							}
						});
						uni.setStorage({
							key: 'location',
							data: {
								latitude: 0,
								//写入默认0，后台判断为空
								longitude: 0
							}
						});
					}
				});
			},
			getOfflineBusinessInfoList() {
				var that = this;
				uni.request({
					url: app.globalData.serviceUrl +
						'/UserMiniProgramController/getOfflineBusinessInfoList',
					method: 'POST',
					data: {
						order_by: 1, // - 查询顺序 0 创建时间(默认) 1 经纬度距离
						order_by_clause: 0, // - 查询顺序方式 0 正序(默认) 1 倒序
						location_type: 1, // - 经纬度类型 0 高德(默认) 1 腾讯
						longitude: this.location ? this.location.longitude : "", // - 经度
						latitude: this.location ? this.location.latitude : "", // - 纬度
						type: 1, // - 类型 0 全部(默认) 1 正常 2 自营 3 自营不展示
						state: 2, // - 状态 0 全部 1 取消 / 删除 2 正常(默认)
						page: this.busPage, // - 当前页（ 可不传 默认第1页）
						page_size: 10, // - 页大小（ 可不传 默认20）
						keyword: '',
						recommend: 1
					},
					header: {
						'content-type': 'application/x-www-form-urlencoded'
					},
					success: (res) => {
						let info = res.data.data;
						if (info && info.length) {
							if (this.busPage == 1) {
								this.goodsList = info
							} else {
								this.goodsList = this.goodsList.concat(info)
							}
						} else {
							this.busMore = false;
						}
					}
				});
			},
			goGoods(item) {
				uni.navigateTo({
					url: "/pages/newIndex/goodsDetail/goodsDetail?item=" + JSON.stringify(item)
				});
			},
			goOrderByid(id) {
				uni.navigateTo({
					url: "/pages/qrCode/qrCode?id=" + id
				})
			},
			onPageScroll(e) {
				this.scrollTop = parseInt(e.scrollTop)
			},
			onReachBottom(e) {
				if (this.busMore) {
					this.setData({
						busPage: this.busPage + 1
					});
					this.getOfflineBusinessInfoList();
				}
			}
		}
	}
</script>

<style scoped lang="scss">
	.btn-info-order {
		border-top: 1px solid #999;

		.tips {
			text-align: center;
			font-size: 16px;
			color: #333;
		}

		.bio {
			width: 200px;
			height: 40px;
			font-size: 18px;
			background: #333;
			color: #fff;
			border-radius: 5px;
			box-shadow: 7px 6px 28px 1px rgba(0, 0, 0, 0.24);
			margin: 20px auto;
			display: flex;
			align-items: center;
			justify-content: center;

			&:active {
				box-shadow: 7px 6px 28px 1px rgba(0, 0, 0, 0.24);
				transform: translateY(4px);
			}
		}
	}

	.list-title {
		font-weight: bold;
		margin: 10px 10px 0;
		padding-left: 5px;
		border-left: 2px solid #333
	}

	.page-info {
		min-height: 100vh;
		width: 100%;
		background: rgba(242, 243, 248, 1);

		::v-deep .uni-steps__column-text {
			border: none;
		}

		.icon-gif {
			width: 100px;
			margin: 20px auto;

			image {
				width: 100%;
			}
		}

		.top-info {
			display: flex;
			align-items: center;
			border-bottom: 1px solid #999;
			padding: 10px 20px;

			.icon {
				width: 50px;
				margin-right: 10px;
			}

			.name {
				font-size: 18px;

				.tip {
					font-size: 14px;
					color: #666;
					margin-top: 10px;
				}
			}
		}

		.mian-btn {
			width: 200px;
			height: 40px;
			text-align: center;
			line-height: 40px;
			font-size: 18px;
			background: #333;
			color: #fff;
			border-radius: 5px;
			box-shadow: 7px 6px 28px 1px rgba(0, 0, 0, 0.24);
			margin: 30px auto;

			&:active {
				box-shadow: 7px 6px 28px 1px rgba(0, 0, 0, 0.24);
				transform: translateY(4px);
			}
		}
	}


	.goods-list {
		padding: 10px;

		.goods-item {
			background: #fff;

			margin: 15px 0;
			border-radius: 10px;
			position: relative;

			::v-deep .loading-img {
				height: 280px;
			}

			::v-deep .easy-loadimage {
				width: 100%;
				border-radius: 10px;

			}

			.label-info {
				position: absolute;
				right: 0;
				top: 0;
				z-index: 99;
				color: #fff;
				background: #222;
				padding: 3px 5px;
				font-size: 12px;
				border-bottom-left-radius: 5px;
			}

			.goods-flex {
				display: flex;
				align-items: flex-end;
				padding: 10px;

				.right {
					flex: 0 0 70px;

					.btn {
						height: 30px;
						line-height: 30px;
						text-align: center;
						border: 1px solid #333;
						border-radius: 5px;
						color: #fff;
						background: #333;
						font-size: 14px;
					}
				}

				.left {
					flex: 1 1 0;
					padding-left: 10px;

					.name {
						font-size: 14px;
						margin: 5px 0;
					}

					.address {
						font-size: 12px;
						color: #666;
						overflow: hidden;
						white-space: nowrap;
						text-overflow: ellipsis;
					}

					.juli {
						font-size: 12px;
						color: #666;

						span {
							margin-left: 15px;
						}
					}
				}
			}


		}
	}
</style>